package com.recipedb.recipedb.controller;

import com.recipedb.recipedb.entity.UserFollow;
import com.recipedb.recipedb.entity.UserFollowId;
import com.recipedb.recipedb.entity.Recipe;
import com.recipedb.recipedb.service.UserFollowService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/api/userfollows")
public class UserFollowController {

    @Autowired
    private UserFollowService service;

    // 基本 CRUD 操作
    @PostMapping
    public ResponseEntity<UserFollow> create(@RequestBody UserFollow entity) {
        return ResponseEntity.ok(service.save(entity));
    }

    @GetMapping
    public ResponseEntity<List<UserFollow>> getAll() {
        return ResponseEntity.ok(service.findAll());
    }

    @GetMapping("/{followerId}/{followeeId}")
    public ResponseEntity<UserFollow> getById(
            @PathVariable Long followerId,
            @PathVariable Long followeeId) {
        UserFollowId id = new UserFollowId(followerId, followeeId);
        Optional<UserFollow> userFollow = service.findById(id);
        return userFollow.map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }

    @DeleteMapping("/{followerId}/{followeeId}")
    public ResponseEntity<Void> delete(
            @PathVariable Long followerId,
            @PathVariable Long followeeId) {
        UserFollowId id = new UserFollowId(followerId, followeeId);
        service.deleteById(id);
        return ResponseEntity.noContent().build();
    }

    // 关注关系查询
    @GetMapping("/follower/{followerId}/followees")
    public ResponseEntity<List<UserFollow>> getFollowees(@PathVariable Long followerId) {
        return ResponseEntity.ok(service.findByFollowerId(followerId));
    }

    @GetMapping("/followee/{followeeId}/followers")
    public ResponseEntity<List<UserFollow>> getFollowers(@PathVariable Long followeeId) {
        return ResponseEntity.ok(service.findByFolloweeId(followeeId));
    }

    // 核心功能：获取关注的用户发布的菜谱
    @GetMapping("/follower/{followerId}/recipes")
    public ResponseEntity<List<Recipe>> getFollowedUsersRecipes(@PathVariable Long followerId) {
        List<Recipe> recipes = service.getFollowedUsersRecipes(followerId);
        return ResponseEntity.ok(recipes);
    }

    // 关注用户
    @PostMapping("/follow")
    public ResponseEntity<?> followUser(
            @RequestParam Long followerId,
            @RequestParam Long followeeId) {
        try {
            boolean success = service.followUser(followerId, followeeId);
            return ResponseEntity.ok().body("关注成功");
        } catch (RuntimeException e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }

    // 取消关注
    @DeleteMapping("/unfollow")
    public ResponseEntity<?> unfollowUser(
            @RequestParam Long followerId,
            @RequestParam Long followeeId) {
        try {
            boolean success = service.unfollowUser(followerId, followeeId);
            return ResponseEntity.ok().body("取消关注成功");
        } catch (RuntimeException e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }

    // 检查是否已关注
    @GetMapping("/check")
    public ResponseEntity<Boolean> isFollowing(
            @RequestParam Long followerId,
            @RequestParam Long followeeId) {
        boolean isFollowing = service.isFollowing(followerId, followeeId);
        return ResponseEntity.ok(isFollowing);
    }

    // 获取用户关注的所有用户ID
    @GetMapping("/follower/{followerId}/followee-ids")
    public ResponseEntity<List<Long>> getFollowedUserIds(@PathVariable Long followerId) {
        List<Long> followeeIds = service.getFollowedUserIds(followerId);
        return ResponseEntity.ok(followeeIds);
    }

    // 获取用户的所有粉丝ID
    @GetMapping("/followee/{followeeId}/follower-ids")
    public ResponseEntity<List<Long>> getFollowerIds(@PathVariable Long followeeId) {
        List<Long> followerIds = service.getFollowerIds(followeeId);
        return ResponseEntity.ok(followerIds);
    }

    // 统计关注数量
    @GetMapping("/follower/{userId}/count")
    public ResponseEntity<Long> getFollowCount(@PathVariable Long userId) {
        long count = service.getFollowCount(userId);
        return ResponseEntity.ok(count);
    }

    // 统计粉丝数量
    @GetMapping("/followee/{userId}/count")
    public ResponseEntity<Long> getFollowerCount(@PathVariable Long userId) {
        long count = service.getFollowerCount(userId);
        return ResponseEntity.ok(count);
    }

    // 直接删除关注关系
    @DeleteMapping("/direct-delete")
    public ResponseEntity<?> deleteByFollowerIdAndFolloweeId(
            @RequestParam Long followerId,
            @RequestParam Long followeeId) {
        boolean deleted = service.deleteByFollowerIdAndFolloweeId(followerId, followeeId);
        if (deleted) {
            return ResponseEntity.ok().body("删除成功");
        } else {
            return ResponseEntity.badRequest().body("删除失败，记录不存在");
        }
    }
}